package org.wiki.jdbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.wiki.jdbc.domain.User;
import org.wiki.jdbc.exception.DAOException;
import org.wiki.jdbc.utils.JdbcUtils;

/**
 * 数据库持久化默认操作实现类，采用JDBC实现。
 * @author Wiki.M
 * @version 0.1
 */
public class UserDAOImpl implements IUserDAO {
	
	/**
	 * 根据ID删除用户对象
	 * @param id 用户ID
	 */
	public void delete(int id) {
		Connection conn = JdbcUtils.getConnection();
		PreparedStatement ps = null;
		try{
			String sql = "delete from user where id=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.execute();
		}catch(SQLException e){
			throw new DAOException("save user failed!");
		}finally{
			JdbcUtils.clear(conn, ps, null);
		}
	}

	/**
	 * 通过name查询User对象，返回User列表。
	 * @param name 用户名称
	 */
	public List<User> queryByName(String name) {
		Connection conn = JdbcUtils.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<User> list = new ArrayList<User>();
		try{
			String sql = "select id,name,password from user where name like ?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, "%"+name+"%");	
			rs =ps.executeQuery();
			User user = null;
			while(rs.next()){
				user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				list.add(user);
			}
		}catch(SQLException e){
			throw new DAOException("save user failed!");
		}finally{
			JdbcUtils.clear(conn, ps, null);
		}
		return list;
		
	}

	/**
	 * 保存用户对象
	 * @param user 用户对象实例
	 */
	public void save(User user) {
		Connection conn = JdbcUtils.getConnection();
		PreparedStatement ps = null;
		try{
			String sql = "insert into user(name,password) values(?,?)";
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getName());
			ps.setString(2, user.getPassword());
			ps.execute();
		}catch(SQLException e){
			throw new DAOException("save user failed!");
		}finally{
			JdbcUtils.clear(conn, ps, null);
		}
	}

	/**
	 * 更新用户对象
	 * @param user 用户对象实例
	 */
	public void update(User user) {
		Connection conn = JdbcUtils.getConnection();
		PreparedStatement ps = null;
		try{
			String sql = "update user set name=?,password=? where id=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getName());
			ps.setString(2, user.getPassword());
			ps.setInt(3, user.getId());
			ps.execute();
		}catch(SQLException e){
			throw new DAOException("save user failed!");
		}finally{
			JdbcUtils.clear(conn, ps, null);
		}	
	}
}